import { Options, Vue } from 'vue-class-component'
import navigator from '@/components/common/navigator.vue'
import store from '@/store'
import { ElMessage } from 'element-plus'
import router from '@/router'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import * as echarts from 'echarts'

interface iSignParams {
  challengeId: number
  userId: number
  conditionSheetId: string
}
interface iSheets {
  conditionSheetId: string
  conditionSheetName: string
  onState: number
  authorId: string
  createTime: Date
  updateTime: Date
}
interface iForm {
  region: string
}
interface iChallenge {
  challengeId: number
  challengeName: string
  introduction: string
  startTime: Date
  endTime: Date
  stockCode: string
  startingFunds: number
  maxParticipantsNumber: number
  participantsNumber: number
  challengeStat: number
  createTime: Date
}
interface iRank {
  userId: string
  account: string
  yield: number
}
interface iCompeteInfo {
  challengeId: number
  userId: number
}
interface iCompeteData {
  day: string
  share: number
  property: number
  capital: number
}

@Options({
  components: {
    navigator
  }
})

export default class challengeDetail extends Vue {
  pageSum = 1
  curPage = 1
  eachPage = 10
  yield = 0
  competeData: iCompeteData[] = []
  per = 0
  dialogFormVisible = false
  sheets: iSheets[]=[]
  tableData: iRank[] = []
  buttonText = '参加挑战赛'
  disabled = false
  challengeInfo: iChallenge = {
    challengeId: 0,
    challengeName: '',
    introduction: '',
    startTime: new Date(),
    endTime: new Date(),
    stockCode: '',
    startingFunds: 0,
    maxParticipantsNumber: 0,
    participantsNumber: 0,
    challengeStat: 0,
    createTime: new Date()
  }

  form: iForm = {
    region: ''
  }

  signParams: iSignParams = {
    challengeId: 0,
    userId: 0,
    conditionSheetId: ''
  }

  competeInfo: iCompeteInfo = {
    challengeId: 0,
    userId: 0
  }

  mounted () {
    const challengeId = parseInt(this.$route.query.challengeId as string)
    const userId = store.state.u.userId
    this.signParams.challengeId = challengeId
    this.signParams.userId = userId
    this.competeInfo.challengeId = challengeId
    this.competeInfo.userId = userId
    store.dispatch('GetChallengeInfo', challengeId)
      .then(response => {
        const code = response.data.code
        if (code === 200) {
          this.challengeInfo = response.data.data
          const dateBegin = new Date(this.challengeInfo.startTime)
          const dateEnd = new Date(this.challengeInfo.endTime)
          const dateNow = new Date()
          const dateDiff = dateEnd.getTime() - dateBegin.getTime()
          const dateDiff2 = dateNow.getTime() - dateBegin.getTime()
          const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
          const dayDiff2 = Math.floor(dateDiff2 / (24 * 3600 * 1000))
          if (dayDiff2 >= dayDiff) {
            this.per = 100
          } else {
            this.per = parseInt((dayDiff2 * 100 / dayDiff).toFixed(2))
          }
          console.log(this.challengeInfo)
          if (this.challengeInfo.challengeStat === 1) {
            this.disabled = true
            this.buttonText = '已结束'
          }
        } else {
          console.log('failed')
        }
      }).catch(() => {
        console.log('connect failed')
      })
    store.dispatch('Compete', this.competeInfo)
      .then(response => {
        const code = response.data.code
        if (code === 200) {
          console.log('正在比赛哦')
          this.competeData = response.data.data.singleBackTestResultVOS
          const data2 = []
          for (const competeItem of this.competeData) {
            // console.log(competeItem.day)
            const dp = [
              competeItem.day,
              competeItem.property.toFixed(1)
            ]
            data2.push({ value: dp })
          }
          const data = []
          // const data2 = [
          //   {
          //     value: [
          //       '1997-10-4 12:00:00',
          //       684
          //     ]
          //   },
          //   {
          //     value: [
          //       '1997-10-5 12:00:00',
          //       200
          //     ]
          //   },
          //   {
          //     value: [
          //       '1997-10-6 12:00:00',
          //       300
          //     ]
          //   },
          //   {
          //     value: [
          //       '1997-10-7 12:00:00',
          //       300
          //     ]
          //   },
          //   {
          //     value: [
          //       '1997-10-8 12:00:00',
          //       300
          //     ]
          //   },
          //   {
          //     value: [
          //       '1997-10-9 12:00:00',
          //       300
          //     ]
          //   }
          // ]
          const myChart = echarts.init(document.getElementById('nowEcharts'))
          const option = {
            title: {
              text: '挑战赛资产走势'
            },
            tooltip: {
              trigger: 'axis',
              formatter: function (params) {
                params = params[0]
                return params.value[0] + ': ' + params.value[1]
              },
              axisPointer: {
                animation: false
              }
            },
            xAxis: {
              name: '时间',
              type: 'time'
              // min: this.competeData[0].day,
              // max: this.competeData[length - 1].day
            },
            yAxis: {
              type: 'value',
              min: function (value) {
                return Math.floor(value.min - 1000)
              },
              max: function (value) {
                return Math.ceil(value.max + 1000)
              },
              boundaryGap: [0, '100%']
            },
            series: [{
              type: 'line',
              showSymbol: false,
              hoverAnimation: false,
              smooth: true,
              data: data
            }]
          }
          myChart.setOption(option)
          setInterval(function () {
            if (data2 === null) {
            } else {
              for (let i = 0; i < 3; i++) {
                data.push(data2.shift())
                if (!data == null) {
                  data.shift()
                }
              }
              myChart.setOption(option)
            }
          }, 500)
        }
        store.dispatch('RealTimeRanking', challengeId)
          .then(response => {
            const code = response.data.code
            if (code === 200) {
              this.tableData = response.data.data
              this.pageSum = Math.ceil(this.tableData.length / this.eachPage)
              console.log(this.tableData)
            } else {
              console.log('failed')
            }
          }).catch(() => {
            console.log('connect failed')
          })
      }).catch(() => {
        console.log('connect failed')
      })
    store.dispatch('getSheets', userId)
      .then(response => {
        console.log(response.data)
        this.sheets = response.data.data
        console.log(this.sheets[0])
      }).catch(() => {
        console.log('connect failed')
      })
  }

  signForChallenge (): void {
    this.dialogFormVisible = false
    console.log(this.form.region)
    this.signParams.conditionSheetId = this.form.region
    store.dispatch('SignForChallenge', this.signParams)
      .then(response => {
        console.log('connect success')
        const code = response.data.code
        const message = response.data.message
        if (code === 200) {
          ElMessage.success({
            message: message,
            type: 'success'
          })
          console.log('报名成功')
          router.push('/challenge')
        } else if (code === 500) {
          ElMessage.warning({
            message: message,
            type: 'warning'
          })
        }
      }).catch(() => {
        console.log('failed')
      })
  }

  handleSizeChange (val) {
    console.log(`每页 ${val} 条`)
    this.curPage = 1
    this.eachPage = val
  }

  // 当前页改变时触发 跳转其他页
  handleCurrentChange (val) {
    console.log(`当前页: ${val}`)
    this.curPage = val
  }
}
